<?php
namespace plugin\ky_shouyin\app\controller;

use support\Request;
use support\Db;

class StoreController extends BaseController
{
    public function index()
    {
        return $this->view('store/index');
    }
    
    public function list(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 15);
        $keyword = $request->input('keyword', '');
        
        $query = Db::table('ky_store');
        
        if ($keyword) {
            $query->where(function($query) use ($keyword) {
                $query->where('name', 'like', "%{$keyword}%")
                      ->orWhere('address', 'like', "%{$keyword}%")
                      ->orWhere('phone', 'like', "%{$keyword}%");
            });
        }
        
        $total = $query->count();
        $stores = $query->offset(($page - 1) * $limit)
                       ->limit($limit)
                       ->orderBy('id', 'desc')
                       ->get();
                       
        return json([
            'code' => 0,
            'msg' => 'success',
            'count' => $total,
            'data' => $stores
        ]);
    }
    
    public function add(Request $request)
    {
        if ($request->method() === 'POST') {
            $data = $request->post();
            
            try {
                // 验证门店名称是否重复
                $exists = Db::table('ky_store')
                    ->where('name', $data['name'])
                    ->exists();
                    
                if ($exists) {
                    throw new \Exception('门店名称已存在');
                }
                
                // 添加门店
                $storeId = Db::table('ky_store')->insertGetId([
                    'name' => $data['name'],
                    'address' => $data['address'],
                    'phone' => $data['phone'],
                    'business_hours' => $data['business_hours'],
                    'manager_name' => $data['manager_name'],
                    'manager_phone' => $data['manager_phone'],
                    'status' => $data['status'],
                    'remark' => $data['remark'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
                
                return json(['code' => 0, 'msg' => '添加成功']);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => '添加失败：' . $e->getMessage()]);
            }
        }
        
        return $this->view('store/add');
    }
    
    public function edit(Request $request)
    {
        if ($request->method() === 'POST') {
            $data = $request->post();
            
            try {
                // 验证门店名称是否重复
                $exists = Db::table('ky_store')
                    ->where('name', $data['name'])
                    ->where('id', '<>', $data['id'])
                    ->exists();
                    
                if ($exists) {
                    throw new \Exception('门店名称已存在');
                }
                
                // 更新门店
                Db::table('ky_store')
                    ->where('id', $data['id'])
                    ->update([
                        'name' => $data['name'],
                        'address' => $data['address'],
                        'phone' => $data['phone'],
                        'business_hours' => $data['business_hours'],
                        'manager_name' => $data['manager_name'],
                        'manager_phone' => $data['manager_phone'],
                        'status' => $data['status'],
                        'remark' => $data['remark'],
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                
                return json(['code' => 0, 'msg' => '编辑成功']);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => '编辑失败：' . $e->getMessage()]);
            }
        }
        
        $id = $request->get('id');
        $store = Db::table('ky_store')->where('id', $id)->first();
        
        return $this->view('store/edit', ['store' => $store]);
    }
    
    public function delete(Request $request)
    {
        $id = $request->post('id');
        
        try {
            // 检查是否有关联数据
            $hasStaff = Db::table('ky_staff')
                ->where('store_id', $id)
                ->exists();
                
            if ($hasStaff) {
                throw new \Exception('该门店下有员工，不能删除');
            }
            
            $hasMember = Db::table('ky_member')
                ->where('store_id', $id)
                ->exists();
                
            if ($hasMember) {
                throw new \Exception('该门店下有会员，不能删除');
            }
            
            $hasOrder = Db::table('ky_order')
                ->where('store_id', $id)
                ->exists();
                
            if ($hasOrder) {
                throw new \Exception('该门店有订单记录，不能删除');
            }
            
            // 删除门店
            Db::table('ky_store')->where('id', $id)->delete();
            
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }
} 